<template>
  <vxe-modal
    resize
    esc-closable
    width="55%"
    height="80%"
    showFooter
    v-model="formVisible"
    @hide="formClose"
    :loading="formLoading"
  >
    <template slot="title">
      <span>模块功能表单</span>
    </template>
    <template>
      <el-scrollbar class="scrollbar-handle">
        <el-tabs tab-position="top" v-model="tabName" :before-leave="tabChange">
          <!-- 模块配置 -->
          <el-tab-pane name="1">
            <span slot="label">
              <i class="el-icon-s-tools"></i> 模块配置
            </span>
            <el-scrollbar class="scrollbar-handle">
              <vxe-form
                ref="firstForm"
                title-width="100"
                title-align="right"
                :data="formEntity"
                :rules="rules"
                span="12"
              >
                <vxe-form-item
                  title="模块编码"
                  field="B_EnCode"
                  :title-suffix="{ message: '模块编码不能重复！', icon: 'fa fa-exclamation-circle' }"
                >
                  <el-input v-model="formEntity.B_EnCode" placeholder="请输入" clearable></el-input>
                </vxe-form-item>
                <vxe-form-item
                  title="模块名称"
                  field="B_FullName"
                  :title-suffix="{ message: '模块名称不能重复！', icon: 'fa fa-exclamation-circle' }"
                >
                  <el-input v-model="formEntity.B_FullName" placeholder="请输入" clearable></el-input>
                </vxe-form-item>
                <vxe-form-item title="所属模块">
                  <rayd-select :options="moduleTreeIds" v-model="formEntity.B_ParentId" tree-config></rayd-select>
                </vxe-form-item>
                <vxe-form-item title="排序码" span="10">
                  <el-input-number :controls="false" :min="0" v-model="formEntity.B_SortCode"></el-input-number>
                </vxe-form-item>
                <vxe-form-item title="模块图标" span="24">
                  <e-icon-picker v-model="formEntity.B_Icon" />
                </vxe-form-item>
                <vxe-form-item title="导航地址" span="24">
                  <el-input v-model="formEntity.B_UrlAddress" placeholder="请输入" clearable></el-input>
                </vxe-form-item>
                <vxe-form-item title="描述" span="24">
                  <el-input
                    type="textarea"
                    :autosize="{ minRows: 4, maxRows: 4}"
                    placeholder="请输入"
                    clearable
                    v-model="formEntity.B_Description"
                  ></el-input>
                </vxe-form-item>
              </vxe-form>
            </el-scrollbar>
          </el-tab-pane>
          <!-- 按钮配置 -->
          <el-tab-pane name="2">
            <span slot="label">
              <i class="el-icon-d-arrow-right"></i> 按钮配置
            </span>
            <el-scrollbar class="scrollbar-handle">
              <vxe-grid
                ref="editTable"
                :height="tableHeight"
                :columns="tableColumn"
                :data="buttonTableData"
                :context-menu="{body: {options: bodyMenus}}"
                edit-config
                :edit-rules="editRules"
                :highlight-current-row="false"
                :mouse-config="{selected: true}"
                :keyboard-config="{isArrow: true, isDel: true, isEnter:true, isTab: true, isEdit: true}"
                :sync-resize="tabName"
              ></vxe-grid>
            </el-scrollbar>
          </el-tab-pane>
        </el-tabs>
      </el-scrollbar>
    </template>
    <template slot="footer">
      <el-button type="primary" @click="()=>{tabName='1'}" :disabled="prevDisabled">上一步</el-button>
      <el-button
        type="primary"
        v-form-validate="()=>{tabName==='2'?formSubmit():tabName='2'}"
      >{{tabName == "2" ? '保 存' : '下一步' }}</el-button>
    </template>
  </vxe-modal>
</template>

<script> 
import { Module } from "@/api";
export default {
  name: "Form",
  props: {},
  data() {
    return {
      //存放表单ref数组
      formArr: ["firstForm", "editTable"],
      //表单可见
      formVisible: false,
      //表单加载中
      formLoading: false,
      //表单实体
      formEntity: {},
      //表单验证规则（规则键必须和表单键一致）
      rules: {
        B_FullName: [
          {
            required: true,
            validator: ({ itemValue, property }) => {
              return new Promise((resolve, reject) => {
                if (this.util.validateNull(itemValue)) {
                  reject(new Error("不能为空！"));
                } else {
                  Module.ValidateExist({
                    id: this.formEntity.B_ModuleId,
                    field: property,
                    value: itemValue,
                  })
                    .then((res) => {
                      resolve();
                    })
                    .catch((err) => {
                      reject(new Error("模块名称已存在！"));
                    });
                }
              });
            },
          },
        ],
        B_EnCode: [
          {
            required: true,
            validator: ({ itemValue, property }) => {
              return new Promise((resolve, reject) => {
                if (this.util.validateNull(itemValue)) {
                  reject(new Error("不能为空！"));
                } else {
                  Module.ValidateExist({
                    id: this.formEntity.B_ModuleId,
                    field: property,
                    value: itemValue,
                  })
                    .then((res) => {
                      resolve();
                    })
                    .catch((err) => {
                      reject(new Error("模块编码已存在！"));
                    });
                }
              });
            },
          },
        ],
      },
      editRules: {
        B_FullName: [{ required: true, message: "请输入名称!" }],
        B_EnCode: [{ required: true, message: "请输入编码!" }],
      },
      /* vxe-grid */
      tableHeight: 400, //表格高度
      buttonTableData: [], //模块按钮表格实体
      //列配置
      tableColumn: [
        {
          field: "B_FullName",
          title: "名称",
          editRender: { name: "ElInput", autoselect: true },
        },
        {
          field: "B_EnCode",
          title: "编码",
          editRender: { name: "ElInput", autoselect: true },
        },
      ],
      //可编辑表格快捷菜单
      bodyMenus: [
        [
          {
            code: "insert",
            name: "插入",
            prefixIcon: "el-icon-plus",
          },
          {
            code: "clear",
            name: "清除",
            prefixIcon: "fa fa-eraser",
          },
          {
            code: "remove",
            name: "删除",
            prefixIcon: "el-icon-delete",
          },
        ],
      ],
      /* 实体数据 */
      moduleTreeIds: [], //模块树型数据
      tabName: "1", //显示的选项卡
      prevDisabled: true, //上一步按钮使能
    };
  },
  created() {
    //初始化
    this.init();
  },
  methods: {
    //初始化
    init() {},
    //表单开启
    formOpen(row, isCopy) {
      this.formVisible = this.formLoading = true; //打开表单
      this.tabName = "1"; //选项卡重置
      this.prevDisabled = true; //禁用上一步按钮
      /* 初始化数据源 */
      let promiseArr = [];
      if (!row) {
        //新增
        this.formEntity.B_SortCode = 0;
      } else {
        //编辑
        this.formEntity = JSON.parse(JSON.stringify(row));
        //加载按钮列表
        promiseArr.push(
          Module.GetButtonList(row.B_ModuleId).then((res) => {
            this.buttonTableData = res;
          })
        );
      }
      //获取模块树形数据
      promiseArr.push(
        Module.GetTreeList(this.formEntity.B_ModuleId).then((res) => {
          this.moduleTreeIds = res;
        })
      );

      Promise.all(promiseArr).then(() => {
        if (isCopy) this.formEntity.B_ModuleId = ""; //复制功能
        this.formLoading = false;
      });
    },
    //表单提交
    formSubmit() {
          //更新当前表格数据
          this.buttonTableData = this.$refs[
            "editTable"
          ].getTableData().fullData;
          //验证通过
          Module.Save({
            moduleEntity: this.formEntity,
            moduleButtonList: this.buttonTableData,
          }).then((res) => {
            this.formVisible = false; //关闭弹窗
            this.$emit("refresh"); //刷新表格
          });
    },
    //表单关闭
    formClose() {
      //清除表单验证
      this.util.formClearValid(this.formArr);
      //数据归位
      Object.assign(this.$data, this.$options.data.call(this))
    },
    //切换标签之前的钩子
    tabChange(activeName, oldActiveName) {
      if (activeName == "1") {
        //第一步了，禁用上一步按钮
        this.prevDisabled = true;
        return true;
      } else if (activeName == "2") {
        //最后一步了，启用用上一步按钮
        this.prevDisabled = false;
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.el-tab-pane {
  height: 60vh;
}
</style>